package com.syp.auth.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

public final class HexStringUtil {
	private static final Logger log = LoggerFactory.getLogger(HexStringUtil.class);
	private static final String CHARSET_UTF8 = "UTF-8";

	/**
	 * 字符串转16进制字符串
	 * 
	 * @param str
	 * @return
	 */
	public static String convert2HexStr(String str) {
		try {
			byte[] bytes = str.getBytes(CHARSET_UTF8);
			StringBuilder sb = new StringBuilder();
			for (byte bt : bytes) {
				String s = Integer.toHexString(bt & 0xFF);
				if (s.length() == 1) {
					sb.append("0");
				}
				sb.append(s.toUpperCase());
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			log.error("str unsupported encoding");
		}
		return null;
	}

	/**
	 * 16进制字符串转字符串
	 * 
	 * @param src
	 * @return
	 */
	public static String convert2Str(String hexStr) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < hexStr.length() / 2; i++) {
			sb.append((char) Integer.valueOf(hexStr.substring(i * 2, i * 2 + 2), 16).byteValue());
		}
		return sb.toString();
	}

}
